<template>
  <div class="add-auth-form">

    <el-form :model="authForm" class="common-form-inline" ref="authFormRef" label-width="100px" :rules="rules">

      <el-form-item label="权限组名称" prop="name" required>
        <el-input class="common-input" v-model="authForm.name" placeholder="请输入权限组名称"></el-input>
      </el-form-item>

      <el-form-item label="所属权限组" prop="parentGroup" required>
        <el-tree-select @node-click="handleNodeClick" check-strictly v-model="authForm.parentGroup" :data="treeData"
          :render-after-expand="false" style="width: 500px" :disabled="isEditMode" />
      </el-form-item>


      <!-- 编辑按钮 -->
      <el-form-item label="后台权限" class="permission-edit-item" prop="permissions">
        <!-- 添加编辑权限按钮 -->
        <div class="edit-permissions-button">
          <el-link v-if="!props.currentAuthData || !props.currentAuthData.hasChildren" :underline="false" type="primary"
            @click="openPermissionDialog">
            编辑
          </el-link>

          <!-- <span v-if="props.currentAuthData && props.currentAuthData.hasChildren" style="color: #999; margin-left: 10px; font-size: 12px;">
            {{ $t('不能编辑父节点权限') }}
          </span> -->

        </div>
        <div class="permission-summary">
          <div v-if="showPermissions" class="permission-list">
            <div class="permission-section" v-if="managementPermissions.length > 0">
              <div class="section-title">具有管理权限:</div>
              <el-tag v-for="permission in managementPermissions" :key="'manage-' + permission.accessRightDefaultId"
                class="permission-tag" type="danger">
                {{ permission.groupName }}
              </el-tag>
            </div>
            <div class="permission-section" v-if="viewOnlyPermissions.length > 0">
              <div class="section-title">具有查看权限:</div>
              <el-tag v-for="permission in viewOnlyPermissions" :key="'view-' + permission.accessRightDefaultId"
                class="permission-tag" type="info">
                {{ permission.groupName }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item>
        <div class="common-group-button">
          <el-button type="primary" class="confirm-button" @click="onSubmit">确认</el-button>
          <el-button class="cancel-button" @click="onCancel">取消</el-button>
        </div>
      </el-form-item>

    </el-form>

    <!-- 权限编辑弹窗 -->
    <permission-edit-dialog ref="permissionDialogRef" :initial-permissions="authForm.permissions"
      @update:permissions="updatePermissions" />

  </div>
</template>

<script setup lang="ts">

import { accessGroupPage, getAccessRight, getListByCreate } from "@/apis/accessGroup";
import { computed, defineEmits, nextTick, onMounted, reactive, ref } from "vue";

import { ElMessage } from "element-plus";
import { useTreeBuilder } from "@/hooks/useTreeBuilder";
import { successTips, errorTips, warningTips } from '@/utils/utils';
import PermissionEditDialog from "./PermissionEditDialog.vue";

const props = defineProps<{
  currentAuthData: any;
}>();

const { treeData, buildTree } = useTreeBuilder();


const emits = defineEmits(["submit", "cancel"]);
const isEditMode = ref(false);
const showPermissions = ref(false); // 控制是否显示权限相关表单项


const getForSelect = () => {
  getListByCreate().then((res) => {
    if (!res.data || res.data.length === 0) {
      return;
    }
    res.data.map((item: any) => {
      item.accessGroupId = item.accessGroupId;
      item.label = item.groupName;
      item.value = item.accessGroupId;
      item.userType = item.userType;
      item.parentGroupId = item.parentGroupId;
      item.description = item.description;
      return item;
    });
    buildTree(res.data);
  });
};


const selectAccessGroupId = ref(0);
const queryAccessGroupIdParentId = ref({});
const handleNodeClick = (data: any) => {
  // 如果是编辑模式，不进行任何操作
  if (isEditMode.value) {
    return;
  }

  selectAccessGroupId.value = data.accessGroupId;

  // 处理节点点击事件
  // 特殊处理：如果是超级管理员节点(accessGroupId=1, parentGroupId=0)，则使用特殊参数
  let queryParams = {
    accessGroupId: data.accessGroupId,
    parentId: data.parentGroupId,
  };
  queryAccessGroupIdParentId.value = queryParams;
  // 如果是超级管理员节点，修改请求参数
  if (data.accessGroupId == 1 && data.parentGroupId == 0) {
    queryParams = {
      accessGroupId: 0,
      parentId: 1,
    };
  }

  getAccessRight(queryParams).then((res) => {
    if (
      !res.data ||
      !res.data.roleRightViewGroupList ||
      res.data.roleRightViewGroupList.length === 0
    ) {
      return;
    }
    // 保存原始权限数据，包括父级权限和当前权限
    const originalRightData = {
      parentRoleRightViewGroupList: res.data.parentRoleRightViewGroupList || [],
      roleRightViewGroupList: res.data.roleRightViewGroupList || [],
    };
    // 将原始权限数据传递给权限编辑弹窗组件
    if (permissionDialogRef.value) {
      permissionDialogRef.value.setOriginalRightData(originalRightData);
    }
    // 转换权限数据格式
    const permissions = res.data.roleRightViewGroupList
      .map((item) => {
        return {
          accessRightDefaultId: Number(item.accessRightDefaultId),
          groupName: item.groupName,
          // accessType: 1代表管理权限，2代表查看权限，0代表无权限
          view: item.accessType === 2,
          manage: item.accessType === 1,
        };
      })
      .filter((item) => item.view || item.manage); // 只保留有权限的项

    // 更新权限数据
    authForm.permissions = permissions;
  });
};

onMounted(() => {
  getForSelect();
  // 如果是编辑模式且有currentAuthData，则直接设置表单数据
  if (isEditMode.value && props.currentAuthData) {
    setFormData(props.currentAuthData);
  }
});

const authFormRef = ref();
const permissionDialogRef = ref();
const authForm = reactive({
  name: "",
  parentGroup: "",
  permissions: [],
  accessGroupId: 0,
});

// 存储从上层传递过来的原始权限数据
const savedOriginalRightData = ref(null);


//权限表单添加规则
const rules = {
  name: [
    { required: true, message: '请输入权限组名称', trigger: "blur" },
    { min: 2, max: 20, message: "长度在2~20个字符之间", trigger: "blur" },
  ],
  parentGroup: [
    {
      required: true,
      message: "请选择所属权限组",
      trigger: "change",
    },
  ],
  permissions: [
    {
      required: true,
      message: "请选择权限",
      trigger: "change",
    },
  ],
};

const managementPermissions = computed(() => {
  if (!authForm.permissions || !Array.isArray(authForm.permissions)) {
    return [];
  }
  return authForm.permissions.filter((p) => p.manage);
});

const viewOnlyPermissions = computed(() => {
  if (!authForm.permissions || !Array.isArray(authForm.permissions)) {
    return [];
  }
  return authForm.permissions.filter((p) => p.view && !p.manage);
});


const updatePermissions = (permissions) => {
  if (Array.isArray(permissions)) {
    // 确保每个权限项都有正确的属性
    authForm.permissions = permissions.map((perm) => ({
      accessRightDefaultId: Number(perm.accessRightDefaultId),
      groupName: perm.groupName || "",
      view: !!perm.view,
      manage: !!perm.manage,
    }));
    // 显示权限相关表单项
    showPermissions.value = true;
    // 如果有选择权限，清除permissions字段的验证状态
    if (permissions.length > 0 && authFormRef.value) {
      // 使用nextTick确保DOM更新后再清除验证
      nextTick(() => {
        authFormRef.value.clearValidate("permissions");
      });
    } else {
      authFormRef.value.validateField("permissions");
    }
  }
};



const openPermissionDialog = () => {
  // 如果当前节点有子节点，禁止编辑权限
  if (props.currentAuthData && props.currentAuthData.hasChildren) {
    warningTips('不能编辑父级节点的权限')
    return;
  }

  if (Array.isArray(authForm.permissions) && authForm.permissions.length > 0) {
    // 统一转换为view/manage格式
    const formattedPermissions = authForm.permissions.map((perm) => {
      // 1. 已经是view/manage格式
      // 2. 从API获取的accessType格式
      if (perm.view !== undefined || perm.manage !== undefined) {
        // 已经是view/manage格式，确保类型正确
        return {
          accessRightDefaultId: Number(perm.accessRightDefaultId),
          groupName: perm.groupName || "",
          view: !!perm.view,
          manage: !!perm.manage,
        };
      } else if (perm.accessType !== undefined) {
        // API返回的accessType格式，需要转换
        return {
          accessRightDefaultId: Number(perm.accessRightDefaultId),
          groupName: perm.groupName || "",
          view: perm.accessType === 2,
          manage: perm.accessType === 1,
        };
      } else {
        // 未知格式，设置为无权限
        return {
          accessRightDefaultId: Number(perm.accessRightDefaultId),
          groupName: perm.groupName || "",
          view: false,
          manage: false,
        };
      }
    });

    // 更新权限数据
    authForm.permissions = formattedPermissions;

  } else {
    warningTips('当前没有权限数据')
  }

  // 编辑模式下，直接使用保存的原始权限数据，不发送请求
  if (isEditMode.value && savedOriginalRightData.value) {


    // 直接使用保存的原始权限数据
    if (permissionDialogRef.value) {
      permissionDialogRef.value.setOriginalRightData(savedOriginalRightData.value);

      setTimeout(() => {
        permissionDialogRef.value.openDialog();
      }, 100);
    } else {
      errorTips("权限树不存在，无法传递数据")
    }

    return;
  }

  // 以下是新增模式的逻辑

  // 如果已经选择了父级权限组，则获取该权限组的权限数据
  if (authForm.parentGroup) {


    // 获取父级权限组的权限数据
    // 使用选择的父级权限组ID作为parentId，保持不变
    // 使用当前选择的accessGroupId或默认值0
    let queryParams = {
      accessGroupId: Number(authForm.accessGroupId) || 0,
      parentId: Number(authForm.parentGroup),
    };

    // 如果父级是超级管理员节点(parentGroupId=1)，特殊处理请求参数 这里不要用三等
    if (authForm.parentGroup == 1) {
      queryParams = {
        accessGroupId: 0,
        parentId: 1,
      };
    }

    getAccessRight(queryParams)
      .then((res) => {


        // 保存原始权限数据，包括父级权限和当前权限
        const originalRightData = {
          parentRoleRightViewGroupList: res.data.parentRoleRightViewGroupList || [],
          roleRightViewGroupList: res.data.roleRightViewGroupList || [],
        };



        // 将原始权限数据传递给权限编辑弹窗组件
        if (permissionDialogRef.value) {
          permissionDialogRef.value.setOriginalRightData(originalRightData);

          // 打开弹窗
          setTimeout(() => {
            // 如果是新增模式，先重置权限选择
            if (!isEditMode.value) {

              permissionDialogRef.value.resetPermissions();
            }
            permissionDialogRef.value.openDialog();
          }, 100);
        } else {
          errorTips("权限树不存在，无法传递数据")
        }
      })
      .catch((error) => {
        errorTips('获取权限数据失败')
      });
  } else {
    // 如果没有选择父级权限组，提示用户先选择
    errorTips('请先选择所属权限组')
  }
};



const onSubmit = () => {
  if (authFormRef.value) {
    authFormRef.value.validate((valid: boolean) => {
      if (valid) {
        // 构造提交的权限数据
        const roleRightGroupList = authForm.permissions.map((permission) => {
          // 转换为API需要的格式
          let accessType = 0; // 默认无权限

          if (permission.manage) {
            accessType = 1; // 管理权限
          } else if (permission.view) {
            accessType = 2; // 查看权限
          }

          return {
            accessRightDefaultId: Number(permission.accessRightDefaultId),
            accessType: accessType,
          };
        });

        // 验证权限列表是否为空
        if (!roleRightGroupList || roleRightGroupList.length === 0) {

          errorTips("请选择权限")
          return;
        }
        // 从缓存中获取用户信息

        const userInfo = JSON.parse(sessionStorage.getItem("meInfo") || "{}");
        // 构造API请求参数
        const requestData: any = {
          name: authForm.name,
          userType: 2, // 后台用户类型
          description: "", // 可以添加描述字段
          roleRightGroupList: roleRightGroupList,
        };

        // 编辑模式需要添加roleId和正确的parentGroupId
        if (isEditMode.value && props.currentAuthData && props.currentAuthData.id) {
          requestData.roleId = props.currentAuthData.id;

          requestData.parentGroupId = authForm.parentGroup;
        } else {
          // 新增模式
          requestData.roleId = null;
          requestData.parentGroupId = authForm.parentGroup;
        }
        if (requestData.parentGroupId === 1) {
          requestData.userType = 2;
        } else {
          requestData.userType = 2;
        }

        if (selectAccessGroupId.value === requestData.roleId) {
          // 提示不能选择自己作为父级权限组
          errorTips("不能选择子级作为父级权限组")
          return;
        }
        accessGroupPage(requestData)

          .then((res) => {

            // 先刷新当前组件中的数据
            getForSelect();

            // 提交成功后刷新 GetListByCreate 数据并通知父组件
            getListByCreate().then((listRes) => {
              // 强制触发父组件刷新
              emits("submit", {
                refresh: true,
                queryAccessGroupIdParentId: queryAccessGroupIdParentId.value,
              });
            })
              .catch((err) => {
                // 即使刷新失败也通知父组件
                emits("submit", {
                  refresh: true,
                  queryAccessGroupIdParentId: queryAccessGroupIdParentId.value,
                });
              });
          });
      }
    });
  }
};


const onCancel = () => {
  emits("cancel");
};



const setEditMode = (isEdit) => {
  isEditMode.value = isEdit;
  // 在编辑模式下显示权限相关表单项，在新增模式下隐藏
  showPermissions.value = isEdit;
};



//编辑模式下暴露传递数据的方法
const setFormData = (formData) => {


  // 重置表单数据
  authForm.name = "";
  authForm.parentGroup = "";
  authForm.permissions = [];
  authForm.accessGroupId = 0;

  // 只在非编辑模式下重置权限显示标志
  if (!isEditMode.value) {
    showPermissions.value = false;
  }

  if (formData) {
    // 设置表单数据
    authForm.name = formData.name || "";
    authForm.accessGroupId = formData.accessGroupId;

    // 优先使用parentGroupId作为父组ID，如果没有则使用父组件传递的数据
    if (formData.parentGroupId) {
      authForm.parentGroup = formData.parentGroupId;
    } else if (formData.id && isEditMode.value) {
      // 在编辑模式下，如果没有parentGroupId，需要保留原有的回显逻辑
      // 这里需要确保formData中包含了正确的父组ID信息
      authForm.parentGroup = formData.parentGroup || "";

      // 如果parentGroup也没有，可以考虑从API获取正确的父组ID
      if (!authForm.parentGroup && formData.id) {
        // 这里可以添加获取父组ID的API调用
      }
    } else {
      // 新增模式或其他情况
      authForm.parentGroup = formData.parentGroup || "";
    }

    // 在编辑模式下，确保显示权限相关表单项
    if (isEditMode.value) {
      showPermissions.value = true;

      // 检查并保存原始权限数据，用于后续编辑权限
      if (formData.parentRoleRightViewGroupList || formData.roleRightViewGroupList) {
        savedOriginalRightData.value = {
          parentRoleRightViewGroupList: formData.parentRoleRightViewGroupList || [],
          roleRightViewGroupList: formData.roleRightViewGroupList || [],
        };
      }
    }

    // 处理方式1：直接使用传递的权限数据数组
    if (formData.permissions && Array.isArray(formData.permissions)) {
      // 直接使用传入的权限数据，确保格式正确
      authForm.permissions = formData.permissions.map((perm) => ({
        accessRightDefaultId: Number(perm.accessRightDefaultId),
        groupName: perm.groupName || "",
        view: !!perm.view,
        manage: !!perm.manage,
      }));
    }
    // 处理方式2：从managePermissions和viewPermissions重建权限数据
    else if (
      (formData.managePermissions && Array.isArray(formData.managePermissions)) ||
      (formData.viewPermissions && Array.isArray(formData.viewPermissions))
    ) {

      // 获取管理权限列表
      const managePerm = formData.managePermissions || [];
      // 获取查看权限列表
      const viewPerm = formData.viewPermissions || [];


      // 从权限组名称列表重建权限数据结构
      // 管理权限
      if (managePerm.length > 0) {
        managePerm.forEach((permName, index) => {
          authForm.permissions.push({
            accessRightDefaultId:
              props.currentAuthData?.accessRightDefaultIds?.manage?.[index] ||
              1000 + index, // 从父组件传递的ID或使用临时ID
            groupName: permName,
            view: false,
            manage: true,
          });
        });
      }

      // 查看权限
      if (viewPerm.length > 0) {
        viewPerm.forEach((permName, index) => {
          authForm.permissions.push({
            accessRightDefaultId:
              props.currentAuthData?.accessRightDefaultIds?.view?.[index] || 2000 + index, // 从父组件传递的ID或使用临时ID
            groupName: permName,
            view: true,
            manage: false,
          });
        });
      }

    } else if (
      formData.roleRightViewGroupList &&
      Array.isArray(formData.roleRightViewGroupList)
    ) {

      const permissions = formData.roleRightViewGroupList
        .filter((item) => item.accessType === 1 || item.accessType === 2) // 只保留有权限的项
        .map((item) => ({
          accessRightDefaultId: Number(item.accessRightDefaultId),
          groupName: item.groupName,
          view: item.accessType === 2, // accessType=2 表示查看权限
          manage: item.accessType === 1, // accessType=1 表示管理权限
        }));

      authForm.permissions = permissions;
    } else {
      // 尝试从API获取权限数据
      if (formData.id && !isEditMode.value) {
        getAccessRight({ accessGroupId: formData.id })
          .then((res) => {
            if (
              !res.data ||
              !res.data.roleRightViewGroupList ||
              res.data.roleRightViewGroupList.length === 0
            ) {

              return;
            }

            // 保存原始权限数据，用于编辑模式下直接使用
            savedOriginalRightData.value = {
              parentRoleRightViewGroupList: res.data.parentRoleRightViewGroupList || [],
              roleRightViewGroupList: res.data.roleRightViewGroupList || [],
            };


            // 转换权限数据格式
            const permissions = res.data.roleRightViewGroupList
              .map((item) => {
                return {
                  accessRightDefaultId: Number(item.accessRightDefaultId),
                  groupName: item.groupName,
                  // accessType: 1代表管理权限，2代表查看权限，0代表无权限
                  view: item.accessType === 2,
                  manage: item.accessType === 1,
                };
              })
              .filter((item) => item.view || item.manage); // 只保留有权限的项

            // 更新权限数据
            authForm.permissions = permissions;

          })
          .catch((err) => {
            errorTips("获取权限数据失败")
          });
      }
    }

    // 如果formData中包含了权限原始数据，直接保存起来
    if (formData.originalRightData) {
      savedOriginalRightData.value = formData.originalRightData;
    }
  }
};


defineExpose({
  setEditMode,
  setFormData,
});

</script>

<style scoped lang="scss">
.add-auth-form {
  :deep(.el-select__wrapper) {
    // background-color: #f4f4f9;
    // box-shadow: none;
  }

  padding-top: 20px;

  .common-form-inline {
    :deep(.el-form-item__label) {
      font-weight: 800;
      font-size: 14px;
      color: #9f9f9f;
    }
  }

  .form-title {
    margin-bottom: 20px;
  }

  .common-input {
    width: 500px;
  }

  // .common-select {
  //   width: 500px;
  // }

  .manager-input {
    .add-text {
      color: #409eff;
      cursor: pointer;
    }
  }

  .permission-container {
    .el-form-item__content {
      display: flex;
      flex-direction: column;
    }
  }

  .permission-line {
    display: flex;
    flex-direction: column;
    margin-bottom: 10px;

    .content {
      font-weight: normal;
      margin-bottom: 5px;
      padding-top: 1px;
      font-weight: 800;
      font-size: 14px;
      color: #02011b;
    }

    .no-permissions {
      color: #999;
      font-size: 14px;
      padding: 5px 0;
    }
  }

  .permission-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 5px;
    min-height: 32px;
  }

  .permission-edit-item {
    :deep(.el-form-item__content) {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
    }

    .el-link {
      font-size: 14px;
      color: #0c6bfa;
    }
  }

  .form-buttons {
    margin-top: 30px;

    .confirm-btn {
      background-color: #f0a563;
      border-color: #f0a563;
      border-radius: 20px;
      padding: 9px 20px;
    }

    .cancel-btn {
      margin-left: 10px;
      border-radius: 20px;
      padding: 9px 20px;
    }
  }
}

.el-tag {
  height: 30px;
  background: #e8f1fe;
  border-radius: 4px;
  color: #020131;
  font-weight: 500;
  font-size: 14px;
  padding: 0 10px;
}

.common-group-button {
  display: block;
  margin-top: 30px;
}

.permission-tag {
  height: 30px;
  padding: 0 12px;
  background: #e8f1fe;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  color: #020131;
  margin-right: 10px;
  margin-bottom: 5px;
}

.section-title {
  font-size: 14px;
  font-weight: 800;
  color: #020131;
  margin-bottom: 12px;
  margin-top: 2px;
}
</style>
